package com.dme.modules.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Optional;

/**
 * @Author: 喜欢编程的代先生
 * @Date: 2022/6/29 15:34
 * @Description: 拒绝侵权
 */
public class InetAddressUtils {

    private static final Logger logger = LoggerFactory.getLogger(InetAddressUtils.class);

    public static void main(String[] args) {
        Optional<InetAddress> optional = InetAddressUtils.getInetAddressByDomain("180.101.49.12");
        InetAddress inetAddress = optional.get();
        byte[] address = inetAddress.getAddress();
        int ipVersion = getIPVersion(address);
        logger.info(String.valueOf(ipVersion));
    }


    /**
     * 通过 域名 获取 InetAddress 对象
     * @param domain
     * @return
     */
    public static Optional<InetAddress> getInetAddressByDomain(String domain){
        try {
            InetAddress inetAddress = InetAddress.getByName(domain);
            return Optional.of(inetAddress);
        } catch (UnknownHostException e) {
            logger.error("could not find address by {}",domain);
        }
        return Optional.empty();
    }

    /**
     * 判断一个 IP 地址是 IPv4 还是 IPv6
     * @param address
     * @return
     */
    public static int getIPVersion(byte[] address){
        if (address.length == 4) return 4;
        if (address.length == 16) return 16;
        return -1;
    }

}
